package com.wondersgroup.core.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.http.ResponseEntity;

import com.fasterxml.jackson.databind.JsonNode;

/**
 * 处理短信发送
 * @author wanglei
 */
public class SMSUtil {
    private SpringRestUtil restUtil = new SpringRestUtil();
    
    public static boolean sendMSG = false;
    public static String sendPath = "http://180.166.152.6:8088/sms";
    public static String sendUser = "shian";
    public static String sendPassword = "123456";
    public static String defaultToken = "6eb28d18e153eba8c6cf8577da1d0342";
    
    public static final String CODE_SUCCESS = "0000";
    public static final String CODE_FAIL = "0001";
    
    public static final String STATUS_WAITING = "0";
    public static final String STATUS_SENDING = "1";
    public static final String STATUS_SEND = "2";
    public static final String STATUS_FAIL = "3";
    
    static {
        try {
            String send = ConfigPropertiesUtil.getValue("sms.send.msg");
            sendMSG = send!=null && "true".equalsIgnoreCase(send);
            String rootPath = ConfigPropertiesUtil.getValue("sms.root.path");
            if(rootPath!=null){
                sendPath = rootPath;
            }
            String user = ConfigPropertiesUtil.getValue("sms.auth.user");
            if(user!=null){
                sendUser = user;
            }
            String password = ConfigPropertiesUtil.getValue("sms.auth.password");
            if(password!=null){
                sendPassword = password;
            }
            String token = ConfigPropertiesUtil.getValue("sms.auth.defaultToken");
            if(token!=null){
                defaultToken = token;
            }
        } catch (Exception e) {
            Logger.getLogger(SMSUtil.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    
    /**
     * 登录验证获取token
     * @param user
     * @param password
     * @return 
     */
    public String auth(String user, String password){
        /*
        try {
            String url = sendPath + "/auth";
            Map<String, String> pars = new HashMap<>();
            pars.put("appkey", user==null?sendUser:user);
            pars.put("apppwd", password==null?sendPassword:password);
            String body = restUtil.convertValueToString(pars);
            
            ResponseEntity<String> response = restUtil.processStringBodyPost(url, body, SpringRestUtil.jsonMediaType, null, null);
            return response.getBody();
        } catch (Exception ex) {
            Logger.getLogger(SMSUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        */
        return defaultToken;
    }
    
    /**
     * 发送即时短信
     * @param token
     * @param content
     * @param mobileList
     * @return 
     */
    public SMSResponse send(String token, String content, List<String> mobileList){
        SMSResponse response = null;
        if(sendMSG){
            try {
                String url = sendPath + "/send?token={token}";
                Map<String, Object> pars = new HashMap<>();
                pars.put("content", content); //短信内容，限制500字
                pars.put("timing", 0); //是否定时短信 1=是，0=否
                pars.put("timing_stmp", ""); //定时短信时间，如果是定时短信则传递时间(如"2014-07-17 00:00:00")，否则传递""(空字符串)
                pars.put("mobile", mobileList); //发送号码集合，限制500个号码
                String body = restUtil.convertValueToString(pars);

                Map<String, String> uriPars = new HashMap<>();
                uriPars.put("token", token);

                ResponseEntity<String> responseData = restUtil.processStringBodyPost(url, body, SpringRestUtil.jsonMediaType, uriPars, null);
                if(responseData.getStatusCode().value()==200){
                    JsonNode jsonNode = restUtil.convertStringToObject(responseData.getBody(), JsonNode.class);
                    if(jsonNode!=null){
                        JsonNode codeNode = jsonNode.get("error_code");
                        if(codeNode!=null && codeNode.asText()!=null && CODE_SUCCESS.equals(codeNode.asText())) {
                            response = restUtil.convertStringToObject(responseData.getBody(), SMSResponse.class);
                        }
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(SMSUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return response;
    }
    
    /**
     * 查询短信状态
     * @param token
     * @param msgIdList
     * @return 
     */
    public SMSResponse searchStatus(String token, List<String> msgIdList){
        SMSResponse response = null;
        try {
            String url = sendPath + "/status?token={token}";
            Map<String, Object> pars = new HashMap<>();
            pars.put("msg_id", msgIdList); //短信回执ID，限制500个
            String body = restUtil.convertValueToString(pars);
            
            Map<String, String> uriPars = new HashMap<>();
            uriPars.put("token", token);
            
            ResponseEntity<String> responseData = restUtil.processStringBodyPost(url, body, SpringRestUtil.jsonMediaType, uriPars, null);
            if(responseData.getStatusCode().value()==200){
                JsonNode jsonNode = restUtil.convertStringToObject(responseData.getBody(), JsonNode.class);
                if(jsonNode!=null){
                    JsonNode codeNode = jsonNode.get("error_code");
                    if(codeNode!=null && codeNode.asText()!=null && CODE_SUCCESS.equals(codeNode.asText())) {
                        response = restUtil.convertStringToObject(responseData.getBody(), SMSResponse.class);
                    }
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(SMSUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return response;
    }

    public SpringRestUtil getRestUtil() {
        return restUtil;
    }

    public void setRestUtil(SpringRestUtil restUtil) {
        this.restUtil = restUtil;
    }
}
